<template>
  <div>
    <q-table
      :data="tableData"
      :columns="columns"
      hide-bottom
      class="stick-last-col"
      style="margin-top: 0"
      separator="cell"
      no-data-label="暂无数据"
      :pagination="{ rowsPerPage: 0 }"
      color="primary"
    >
      <template v-slot:header-cell-duration="props">
        <q-th>
          {{ props.col.label }}
          <q-icon
            name="iconfont icontubiao-72"
            class="font-18 text-grey"
            style="margin-left: 1px"
          >
            <q-tooltip
              >持续时长：持续时长为0，指参数的值达到阈值判断条件时，立刻触发报警；持续时长不为0，指参数的值达到阈值判断条件且持续时长满足设定条件，才会触发报警</q-tooltip
            >
          </q-icon>
        </q-th>
      </template>
      <template v-slot:header-cell-frequency="props">
        <q-th>
          {{ props.col.label }}
          <q-icon
            name="iconfont icontubiao-72"
            class="font-18 text-grey"
            style="margin-left: 1px"
          >
            <q-tooltip
              >消息推送频率：在此时间段内，无论触发多少次报警，只推送一次消息（避免因频繁报警，导致频繁的消息推送）</q-tooltip
            >
          </q-icon>
        </q-th>
      </template>
      <template v-slot:body-cell-label="{ row }">
        <q-td class="name-class">
          <q-select
            v-model="row.label"
            :options="labelOptions"
            dense
            options-dense
            class="form-select"
            style="margin-top: -5px"
            emit-value
            map-options
            :disable="editRuleFlag"
            outlined
            :rules="[
              (val) => {
                let msg = validateRules['label'].validate(val)
                if (msg && msg.length > 0) {
                  return msg
                }
                return null
              }
            ]"
          >
            <template v-slot:no-option>
              <div class="no-option" />
            </template>
          </q-select>
          <label style="position: absolute; top: 40px">{{
            addr && '点位地址: ' + addr
          }}</label>
        </q-td>
      </template>
      <template v-slot:body-cell-pointCondition="{ row }">
        <q-td class="point-condition">
          <div class="point-condition-div">
            <q-select
              v-model="row.pointCondition"
              :options="conditionOptionsData"
              dense
              options-dense
              lazy-rules
              class="form-select"
              emit-value
              map-options
              outlined
              :rules="[
                (val) => {
                  let msg = checkNotNull(val)
                  if (msg.length > 0) {
                    return msg
                  }
                  return null
                }
              ]"
            >
              <template v-slot:no-option>
                <div class="no-option" />
              </template>
            </q-select>
            <q-input
              class="input-value"
              v-model="row.avalue"
              v-if="showA(row)"
              dense
              emit-value
              map-options
              outlined
              placeholder="A"
              :rules="[
                (val) => {
                  let msg = validateRules['avalue'].validate(val)
                  if (msg && msg.length > 0) {
                    return msg
                  }
                  return null
                }
              ]"
            >
            </q-input>
            <q-input
              class="input-value"
              v-model="row.bvalue"
              dense
              v-if="showB(row)"
              emit-value
              map-options
              outlined
              placeholder="B"
              :rules="[
                (val) => {
                  let msg = validateRules['bvalue'].validate(val)
                  if (msg && msg.length > 0) {
                    return msg
                  }
                  return null
                }
              ]"
            >
            </q-input>
          </div>
        </q-td>
      </template>
      <template v-slot:body-cell-duration="{ row }">
        <q-td class="duration">
          <div class="duration-div">
            <q-input
              v-model="row.duration"
              dense
              emit-value
              map-options
              outlined
              style="margin-top: -5px"
              :rules="[
                (val) => {
                  if (val === null || val === undefined || val === '') {
                    return '请输入'
                  }
                  if (!/^\d+$/g.test(val)) {
                    return '只能输入数字'
                  }
                  return null
                }
              ]"
            >
            </q-input>
            <label class="duration-label">s</label>
          </div>
        </q-td>
      </template>
      <template v-slot:body-cell-frequency="{ row }">
        <q-td class="frequency">
          <q-select
            v-model="row.frequency"
            :options="frequencyOptions"
            dense
            options-dense
            lazy-rules
            class="form-select"
            emit-value
            map-options
            outlined
            style="margin-top: -5px"
            :rules="[
              (val) => {
                let msg = checkNotNull(val)
                if (msg.length > 0) {
                  return msg
                }
                return null
              }
            ]"
          >
            <template v-slot:no-option>
              <div class="no-option" />
            </template>
          </q-select>
        </q-td>
      </template>
    </q-table>
    <div
      id="condition-img"
      v-if="imageSrc !== null"
      :style="{
        backgroundImage: `url(../../../statics/img/threshold/${imageSrc}.png)`
      }"
    >
      <label id="condition-text"> 判断条件图形示例: </label>
      <label
        id="condition-a"
        v-if="showA(this.model)"
        :style="conditionAStyle"
        >{{ this.model.avalue }}</label
      >
      <label
        id="condition-b"
        v-if="showB(this.model)"
        :style="conditionBStyle"
        >{{ this.model.bvalue }}</label
      >
    </div>
  </div>
</template>
<script>
import { map2Operator } from 'src/boot/common/operatorUtils'
export default {
  name: 'plc-threshold-set-dialog-single',
  props: {
    show: {
      type: Boolean,
      default: false
    },
    nameOptions: {
      type: Array,
      require: true
    },
    model: {
      type: Object,
      require: true
    },
    selectedLabels: {
      type: Array
    },
    editRuleFlag: {
      type: Boolean
    }
  },
  emit: ['close'],
  model: {
    prop: 'model',
    event: 'submit'
  },
  computed: {
    tableData () {
      if (this.show) {
        this.handleYzOperators()
        return [this.model]
      }
      return []
    },
    addr () {
      if (this.nameOptions) {
        let op = this.nameOptions.find(n => n.label === this.model.label)
        if (op) {
          return op.addr
        }
      }
      return ''
    },
    conditionOptionsData () {
      // 9 string 2 char
      if (this.getDataType() === 9 || this.getDataType() === 2) {
        // eslint-disable-next-line vue/no-side-effects-in-computed-properties
        this.model.pointCondition = 7
        return [
          { label: '等于', value: 7 }
        ]
      }
      return this.conditionOptions
    },
    labelOptions () {
      if (this.selectedLabels) {
        let options = this.nameOptions ?? []
        return options.filter(o => !this.selectedLabels.includes(o.label))
      }
      return this.nameOptions ?? []
    },
    imageSrc () {
      const srcMap = {
        '5': 'largeThen',
        '8': 'largeEqual',
        '4': 'lessThen',
        '9': 'lessEqual',
        '7': 'equal',
        '1': 'within',
        '10': 'withinA',
        '11': 'withinB',
        '12': 'withinAB',
        '6': 'outside',
        '13': 'outsideB',
        '14': 'outsideA',
        '15': 'outsideAB'
      }
      if (Object.keys(srcMap).includes(this.model.pointCondition?.toString())) {
        return srcMap[this.model.pointCondition]
      }
      return null
    },
    conditionAStyle () {
      if (['4', '9'].includes(this.model.pointCondition?.toString())) {
        return {
          position: 'absolute',
          left: '362px',
          top: '258px'
        }
      }
      if (this.model.pointCondition?.toString() === '7') {
        return {
          position: 'absolute',
          left: '362px',
          top: '254px'
        }
      }
      return {
        position: 'absolute',
        left: '284px',
        top: '254px'
      }
    },
    conditionBStyle () {
      if (['5', '8'].includes(this.model.pointCondition?.toString())) {
        return {
          position: 'absolute',
          left: '365px',
          top: '254px'
        }
      }
      return {
        position: 'absolute',
        left: '430px',
        top: '254px'
      }
    }
  },
  data () {
    return {
      conditionOptions: [
        // { label: '开关OFF', value: 2 },
        // { label: '开关ON', value: 3 },
        { label: '大于', value: 5 }, // b
        { label: '大于等于', value: 8 }, // b
        { label: '小于', value: 4 }, // a
        { label: '小于等于', value: 9 }, // a
        { label: '等于', value: 7 }, // a
        { label: '区间内（A&ltX&ltB）', value: 1 },
        { label: '区间内（A≤X&ltB）', value: 10 },
        { label: '区间内（A&ltX≤B）', value: 11 },
        { label: '区间内（A≤X≤B）', value: 12 },
        { label: '区间外（X&ltA或X&gtB）', value: 6 },
        { label: '区间外（X&ltA或X≥B）', value: 13 },
        { label: '区间外（X≤A或X&gtB）', value: 14 },
        { label: '区间外（X≤A或X≥B）', value: 15 }
      ],
      frequencyOptions: [
        { label: '全部推送', value: 0 },
        { label: '1分钟/次', value: 60 },
        { label: '3分钟/次', value: 3 * 60 },
        { label: '5分钟/次', value: 5 * 60 },
        { label: '10分钟/次', value: 10 * 60 },
        { label: '30分钟/次', value: 30 * 60 }
      ],
      columns: [
        { name: 'label', label: '参数', align: 'center', field: 'label' },
        {
          name: 'pointCondition',
          label: '判断条件',
          align: 'center',
          field: 'pointCondition'
        },
        {
          name: 'duration',
          label: '持续时长',
          align: 'center',
          field: 'duration'
        },
        {
          name: 'frequency',
          label: '消息推送频率',
          align: 'center',
          field: 'frequency'
        }
      ],
      validateRules: {
        label: {
          validate: (v) => {
            if (this.checkNotNull(v).length > 0) {
              return '请选择参数'
            }
            return ''
          }
        },
        avalue: {
          validate: (avalue) => {
            if (this.showA(this.model)) {
              if (this.checkNotNull(avalue).length > 0) {
                return 'A值不能为空'
              }
              if (this.getDataType() !== 9) {
                if (!/^(-?\d+)(\.\d+)?$/g.test(avalue)) {
                  return 'A值只能输入数字'
                }
              }
            }
            return ''
          }
        },
        bvalue: {
          validate: (bvalue) => {
            if (this.showB(this.model)) {
              if (this.checkNotNull(bvalue).length > 0) {
                return 'B值不能为空'
              }
              if (this.getDataType() !== 9) {
                if (!/^(-?\d+)(\.\d+)?$/g.test(bvalue)) {
                  return 'B值只能输入数字'
                }
              }
            }
            return ''
          }
        }
      }
    }
  },
  methods: {
    getDataType () {
      if (this.nameOptions) {
        let op = this.nameOptions.find(n => n.label === this.model.label)
        if (op) {
          return op.dataType
        }
      }
      return ''
    },
    submit () {
      // 校验数据
      for (const key in this.validateRules) {
        const val = this.model[key]
        const rule = this.validateRules[key]
        let validateMessage = rule.validate(val)
        if (validateMessage.length > 0) {
          this.$message.warning(validateMessage)
          return
        }
      }
      this.handleYzOperators()
      this.$emit('submit', this.model)
      this.$emit('close')
    },
    checkNotNull (val) {
      if (val === null || val === undefined || val.toString() === '') {
        return '不能为空'
      }
      return ''
    },
    // 是否显示a输入框
    showA (row) {
      const aArr = [1, 4, 6, 7, 9, 10, 11, 12, 13, 14, 15]
      return aArr.indexOf(row.pointCondition) > -1
    },
    // 是否显示B输入框
    showB (row) {
      const bArr = [1, 5, 6, 8, 10, 11, 12, 13, 14, 15]
      return bArr.indexOf(row.pointCondition) > -1
    },
    handleYzOperators () {
      this.model.yzOperator = map2Operator(this.model.pointCondition, this.model.label, this.model.avalue, this.model.bvalue, null, this.getDataType() === 9)
    }
  }
}
</script>
<style scoped lang="scss">
#condition-img {
  display: flex;
  width: 800px;
  height: 100px;
  #condition-a {
    display: flex;
  }

  #condition-b {
    display: flex;
  }
}

.name-class {
  width: 100px;
  height: 65px;
  max-width: 200px;
}

.point-condition {
  width: 350px;

  .point-condition-div {
    display: flex;
    margin-top: -5px;

    .input-value {
      width: 24%;
      margin-left: 2px;
    }
  }
}

.duration {
  width: 100px;

  .duration-div {
    display: flex;

    input {
      width: 20%;
    }

    .duration-label {
      margin-left: 3px;
      font-size: 18px;
      margin-top: -5px;
      text-align: center;
      align-items: center;
    }
  }
}

.frequency {
  width: 100px;
}
</style>
